package com.oa.official.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.oa.official.mapper.SysUserMapper;
import com.oa.official.service.SysMenuService;
import com.oa.official.service.SysUserService;
import com.oa.official.common.enums.AppHttpCodeEnum;
import com.oa.official.common.exception.CustomException;
import com.oa.official.common.utils.JwtHelper;
import com.oa.official.common.utils.MD5;
import com.oa.official.entity.system.SysUser;
import com.oa.official.response.Result;
import com.oa.official.vo.system.LoginVo;
import com.oa.official.vo.system.RouterVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "登录")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysMenuService sysMenuService;


    @ApiOperation(value = "登录接口")
    @PostMapping(path = "/login")
    public Result login(@RequestBody LoginVo loginVo) {

//        Map<String,Object> map2 = new HashMap<>();
//        map2.put("token","admin-token");

        //1 获取输入用户名和密码
        //2 根据用户名查询数据库
        String username = loginVo.getUsername();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername, username);
        SysUser sysUser = sysUserMapper.selectOne(wrapper);

        //3 用户信息是否存在
        if (sysUser == null) {
            throw new CustomException(AppHttpCodeEnum.LOGIN_USER_NOT_FIND);
        }

        //4 判断密码
        //数据库存密码（MD5）
        String password_db = sysUser.getPassword();
        //获取输入的密码
        String password_input = MD5.encrypt(loginVo.getPassword());
        if (!password_db.equals(password_input)) {
            throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

        //5 判断用户是否被禁用  1 可用 0 禁用
        if (sysUser.getStatus() == 0) {
            throw new CustomException(AppHttpCodeEnum.LOGIN_USER_NOT_STATUS);
        }
        //6 使用jwt根据用户id和用户名称生成token字符串
        String token = JwtHelper.createToken(sysUser.getId(), sysUser.getUsername());
        //7 返回
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return Result.success(map);
    }

    @ApiOperation(value = "获取用户信息")
    @GetMapping(path = "/info")
    public Result info(HttpServletRequest request) {
//        Map<String, Object> map = new HashMap<>();
//        map.put("roles", "[admin]");
//        map.put("introduction", "I am a super administrator");
//        map.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
//        map.put("name", "SuperAdmin");

        //1 从请求头获取用户信息（获取请求头token字符串）
        String token = request.getHeader("X-Token");

        //2 从token字符串获取用户id 或者 用户名称
        Long userId = JwtHelper.getUserId(token);

        //3 根据用户id查询数据库，把用户信息获取出来
        SysUser sysUser = sysUserMapper.selectById(userId);

        //4 根据用户id获取用户可以操作菜单列表
        //查询数据库动态构建路由结构，进行显示
        List<RouterVo> routerList = sysMenuService.findUserMenuListByUserId(userId);
        //5 根据用户id获取用户可以操作按钮列表
        List<String> permsList = sysMenuService.findUserPermsByUserId(userId);

        //6 返回相应的数据
        Map<String, Object> map = new HashMap<>();
        map.put("roles","[admin]");
        map.put("name",sysUser.getName());
        map.put("avatar","https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
        //返回用户可以操作菜单
        map.put("routers",routerList);
        //返回用户可以操作按钮
        map.put("buttons",permsList);
        return Result.success(map);
    }

    @ApiOperation(value = "退出登录")
    @PostMapping(path = "/logout")
    public Result logout(HttpServletRequest request, HttpServletResponse response) {
        return Result.success();
    }
}